﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

namespace ReactiveLang
{
    public sealed class Variable<T> : IAssignableExpression<T>
    {
        Expression.Subject<T> _listeners = new Expression.Subject<T>();
        public bool HasValue { get; private set; }
        T _value;
        public T Value
        {
            get { return _value; }
            set 
            {
                _value = value;
                HasValue = true;
                _listeners.OnValue(value);
            }
        }

        public Variable() { }
        public Variable(T value)
        {
            HasValue = true;
            _value = value;
        }
        
        public IDisposable Activate(IExpressionObserver<T> observer)
        {
            if (HasValue)
                observer.OnValue(Value);
            return _listeners.Activate(observer);
        }
        void IAssignableExpression<T>.Assign(T value)
        {
            Value = value;
        }

        public override string ToString()
        {
            return "{ " + Value + " }";
        }
    }
}
